package com.kosugi.fingercoin;

import android.app.Activity;
import android.graphics.PointF;

import android.os.Bundle;
import android.os.SystemClock;

import android.content.Context;
import android.view.MotionEvent;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import javax.microedition.khronos.opengles.GL11;

import android.opengl.GLES20;
import android.opengl.GLSurfaceView;
import android.opengl.GLU;
import android.opengl.Matrix;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.nio.ShortBuffer;

public class FingerCoin extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mGLView = new ClearGLSurfaceView(this);
        mGLView.setWorld(mWorld);
        setContentView(mGLView);
        
        initShape();
        
        System.out.println("Finger coin initialized");
    }

    @Override
    protected void onPause() {
        super.onPause();
        mGLView.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mGLView.onResume();
    }
    

    
    public void initShape() {
    	Shape.connect(mWorld, e1);
    	e1.setPosition(3, 3, 0);
    	e1.setColor(1f, 0.5f, 0.5f);
    	e1.setAlpha(1f);
    }
    
    public Shape mWorld = new Shape();
    public Ellipse e1 = new Ellipse();

    private ClearGLSurfaceView mGLView;
}

class ClearGLSurfaceView extends GLSurfaceView {
    public ClearGLSurfaceView(Context context) {
        super(context);
        
        mRenderer = new ClearRenderer();
        setRenderer(mRenderer);
    }
    
    boolean isShapePressed = false;
    Shape dragController;    
    Shape selectedShape;
    ClearRenderer mRenderer;

    
    @Override
    public boolean onTouchEvent(final MotionEvent event) {
        queueEvent(new Runnable(){
            public void run() {
            	float[] wPos = new float[3];
            	
            	mRenderer.ScreenToWorld(event.getX(), event.getY(), wPos);
            	
            	float x = wPos[0];
            	float y = wPos[1];
            	
            	if(event.getAction() == event.ACTION_DOWN) {
	            	System.out.println("Mouse Down : " + event.getX() + "," + event.getY());

	            	
	            	Shape shape = mRenderer.getWorld().getHitted(x, y);
	            	if(shape != null) {
	            		System.out.println("mouse hitted");
	            		
	            		//shape.setVelocity(0f, -100f, 0);
	            		isShapePressed = true;
	            		selectedShape = shape;
	            		
	            		if(dragController == null) {
	            			dragController = new Ellipse();
	            		}
	            		
	            		Shape.connect(mRenderer.getWorld(), dragController);
	            		dragController.setPosition(x, y, 0f);
	            		dragController.setColor(0.2f, 0.2f, 1);
	            		dragController.setAlpha(0.5f);
	            		
	            		
	            	}
	            	else
	            		System.out.println("mouse hitted no shape");
            	} 
            	else if(event.getAction() == event.ACTION_MOVE) {
            		if(isShapePressed == true) {
            			//Handling Drag
            			float shapePos[] = selectedShape.pos;
            			
            			float diffx = x - shapePos[0];
            			float diffy = y - shapePos[1];
            			
            			float length = (float)Math.sqrt(diffx * diffx + diffy * diffy);
            			
            			System.out.println("drag length = " + length);
            			float limit = 4f;
            			
            			if(length > limit) {
            				float rate = limit / length;
            				diffx = diffx * rate;
            				diffy = diffy * rate;
            				

                			x = shapePos[0] + diffx;
                			y = shapePos[1] + diffy;
            			}
            			
            			
            			
            			
            			dragController.setPosition(x, y, 0f);
            		}
            	} else if(event.getAction() == event.ACTION_UP) {
            		if(isShapePressed == true) {
            			float shapePos[] = selectedShape.pos;
            			
            			float diffx = x - shapePos[0];
            			float diffy = y - shapePos[1];
            			
            			float length = (float)Math.sqrt(diffx * diffx + diffy * diffy);

            			if(length > 1) {
            				float velFactor = 20;
            				selectedShape.setVelocity(-velFactor * diffx, -velFactor * diffy, 0);
            			}
            			
	            		mRenderer.getWorld().disconnectChild(dragController);
	            		isShapePressed = false;
	            		selectedShape = null;
            		}
            	}
            	
            	
            	
            }});
    	
    	//System.out.println("Mouse Down : " + event.getX() + "," + event.getY());
    	
        return true;
    }
    
    public void setWorld(Shape w) {
    	mRenderer.setWorld(w);
    	
    }


    
}


class ClearRenderer implements GLSurfaceView.Renderer {	  
	  
	private boolean mTranslucentBackground;
	private Cube mCube;
	private Ellipse mEllipse;
	private float mAngle;
	  
	public ClearRenderer() {
        mCube = new Cube();
        mEllipse = new Ellipse();
	}
	
	public void setWorld(Shape w) {
		mWorld = w;
	}
	
	public Shape getWorld() {
		return mWorld;
	}
	
	public void onSurfaceCreated(GL10 gl, EGLConfig config) {
        /*
         * By default, OpenGL enables features that improve quality
         * but reduce performance. One might want to tweak that
         * especially on software renderer.
         */
        gl.glDisable(GL10.GL_DITHER);

        /*
         * Some one-time OpenGL initialization can be made here
         * probably based on features of this particular context
         */
         gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT,
                 GL10.GL_FASTEST);

         if (mTranslucentBackground) {
             gl.glClearColor(0,0,0,0);
         } else {
             gl.glClearColor(1,1,1,1);
         }
         gl.glEnable(GL10.GL_CULL_FACE);
         gl.glShadeModel(GL10.GL_SMOOTH);
         gl.glEnable(GL10.GL_DEPTH_TEST);	
	}
	 
	public void onSurfaceChanged(GL10 gl, int width, int height) {
		this.width = width;
		this.height = height;
		
        gl.glViewport(0, 0, width, height);

        /*
         * Set our projection matrix. This doesn't have to be done
         * each time we draw, but usually a new projection needs to
         * be set when the viewport is resized.
         */

        float ratio = (float) width / height;
        gl.glMatrixMode(GL10.GL_PROJECTION);
        gl.glLoadIdentity();
        gl.glFrustumf(-ratio, ratio, -1, 1, 1, 100);
        

        
       
	}
	
	public void updateMatrices(GL10 gl) {
		GL11 gl11 = (GL11)gl;
		int[] bits = new int[16];
		
		gl11.glGetIntegerv(gl11.GL_MODELVIEW_MATRIX_FLOAT_AS_INT_BITS_OES, bits, 0);
    	for(int i = 0; i < bits.length; i++){
    		model[i] = Float.intBitsToFloat(bits[i]);
    	}
    	
    	
    	
    	gl11.glGetIntegerv(gl11.GL_PROJECTION_MATRIX_FLOAT_AS_INT_BITS_OES, bits, 0);
    	for(int i = 0; i < bits.length; i++){
    		proj[i] = Float.intBitsToFloat(bits[i]);
    	}
    	
	}
	
	private void printMatrices() {
    	System.out.println("Model Matrix : ");
    	
    	String str = new String();
    	for(int i = 0; i < model.length; i++){
    		str += String.valueOf(model[i]);
    		if(i < model.length -1 )
    			str += ",";
    	}
    	
    	System.out.println(str);
    	
    	System.out.println("Project Matrix : ");
    	
    	str = "";
    	for(int i = 0; i < proj.length; i++){
    		str += String.valueOf(proj[i]);
    		if(i < proj.length -1 )
    			str += ",";
    	}
    	
    	System.out.println(str);
	}
	
	public void ScreenToWorld(float curX, float curY, float wRslt[]) {
		
		System.out.println("Screen : " + curX + "," + curY);
		System.out.println("Screen size : " + width + "," + height);
		
    	float[] ret = new float[4];
    	GLU.gluUnProject(curX, curY, offsetZ, model, 0, proj, 0, new int[]{0, 0, width, height}, 0, ret, 0);
    	System.out.println("is OK");
		
    	wRslt[0] = ret[0] * ret[3];
    	wRslt[1] = - ret[1] * ret[3];
    	wRslt[2] = ret[2] * ret[3];
    	
    	System.out.println("-->World : " + wRslt[0] + "," + wRslt[1] + "," + wRslt[2] + ", " + ret[3]);
    	
    	printMatrices();
	}
	 
	public void onDrawFrame(GL10 gl) { 
		
		long curTime = System.currentTimeMillis();
		long elapsedTime;
		
		if(oldTime == 0) {
			elapsedTime = 0;
		} else {
			elapsedTime = curTime - oldTime;
			mWorld.updatePosition(elapsedTime);
		}
		
		oldTime = curTime;
		
		
		
		
        /*
         * Usually, the first thing one might want to do is to clear
         * the screen. The most efficient way of doing this is to use
         * glClear().
         */

        gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);

        /*
         * Now we're ready to draw some 3D objects
         */

        gl.glMatrixMode(GL10.GL_MODELVIEW);
        gl.glLoadIdentity();
        
        //gl.glTranslatef(0, 0, -3.0f);
        gl.glTranslatef(0, 0, offsetZ);
        //gl.glRotatef(mAngle,        0, 1, 0);
        //gl.glRotatef(mAngle*0.25f,  1, 0, 0);

        gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
        gl.glEnableClientState(GL10.GL_COLOR_ARRAY);

        //mCube.draw(gl);
        //mEllipse.draw(gl);
        mWorld.draw(gl);
        
        
        updateMatrices(gl);
        
	}
	
	private Shape mWorld;
	
	private float[] model = new float[16];
	private float[] proj = new float[16];
	private int width;
	private int height;
	
	private float offsetZ = -20f;
	
	private long oldTime = 0;
	

}